package com.bookseek.xreader.views.adapter;

import android.annotation.SuppressLint;
import android.text.SpannableString;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bookseek.xreader.R;
import com.bookseek.xreader.consts.XreaderConts;
import com.bookseek.xreader.utils.DLog;
import com.bookseek.xreader.utils.DxmItemClickListener;
import com.bookseek.xreader.utils.JkhlUtils;
import com.bookseek.xreader.vo.BookListItemVo;
import com.bookseek.xreader.vo.TraceTextVo;

import java.util.List;

public class BdocLoadMoreAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    // 数据类型
    private static final int TYPE_ITEM = 0;
    // 加载更多类型
    private static final int TYPE_LOAD_MORE = 1;

    // 加载状态
    public static final int LOADING = 1; // 加载中
    public static final int LOADING_COMPLETE = 2; // 加载完成
    public static final int LOADING_ERROR = 3; // 加载失败
    public static final int LOADING_END = 4; // 没有更多数据

    private int loadState = LOADING_COMPLETE;

    private List<BookListItemVo> datas;

    private DxmItemClickListener clickListener;

    private String btype;

    public BdocLoadMoreAdapter(List<BookListItemVo> datas,DxmItemClickListener clickListener,String btype) {
        this.datas = datas;
        this.clickListener = clickListener;
        this.btype = btype;
    }

    public BookListItemVo getItem(int pos){
        return datas != null && datas.size() > pos ? datas.get(pos) : null;
    }
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            // 加载数据项布局
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.book_list_item, parent, false);
            return new ItemViewHolder(view);
        } else {
            // 加载底部加载更多布局
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_load_more_footer, parent, false);
            return new LoadMoreViewHolder(view);
        }
    }

    private SpannableString highLightTexts(List<TraceTextVo> lines, String colorLevel){
        if(lines == null || lines.isEmpty()){
            return new SpannableString("");
        }
        StringBuffer sb = new StringBuffer();
        lines.forEach(d->{
            sb.append(JkhlUtils.toStr(d.text));
        });
        String line = sb.toString();
        int strLen = line.length();
        SpannableString spanText = new SpannableString(line);
        //标题颜色
        if("first".equalsIgnoreCase(colorLevel)){
            spanText.setSpan(XreaderConts.FIRST_TEXT_COLOR,0,strLen, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        //
        if("second".equalsIgnoreCase(colorLevel)){
            spanText.setSpan(XreaderConts.SECOND_TEXT_COLOR,0,strLen,Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        for(TraceTextVo textVo : lines){
            if(textVo.showColor != null && textVo.showColor == 1){
                if(textVo.startIndex != null && textVo.endIndex != null && textVo.startIndex >= 0 && textVo.endIndex <= strLen){
                    spanText.setSpan(XreaderConts.HIGHLIGHT_TEXT_COLOR,textVo.startIndex,textVo.endIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                }
            }
        }
        return spanText;
    }


    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ItemViewHolder) {
            // 绑定数据
            BookListItemVo itemVo = datas.get(position);
            ItemViewHolder itemHolder =  ((ItemViewHolder) holder);
            itemHolder.btitleTv.setText(highLightTexts(itemVo.btitleTexts,"first"));
            if(XreaderConts.BTYPE_DIANJI.equalsIgnoreCase(btype)){
                itemHolder.bcontTv.setVisibility(View.GONE);
            }else{
                itemHolder.bcontTv.setText(highLightTexts(itemVo.bcontTexts,"second"));
            }


            itemHolder.bauthorChaoTv.setText(highLightTexts(itemVo.bauthorTexts,"second"));
            if(JkhlUtils.notBlank(itemVo.bchao)){
                String bchao = "["+itemVo.bchao+"] ";
                itemHolder.bchaoTv.setText(bchao);
            }

        } else if (holder instanceof LoadMoreViewHolder) {
            // 根据加载状态更新底部布局
            LoadMoreViewHolder loadMoreViewHolder = (LoadMoreViewHolder) holder;

            switch (loadState) {
                case LOADING:
                    // 显示加载中
                    loadMoreViewHolder.progressBar.setVisibility(View.VISIBLE);
                    loadMoreViewHolder.tvLoadText.setVisibility(View.VISIBLE);
                    loadMoreViewHolder.tvLoadText.setText("加载中...");
                    break;
                case LOADING_COMPLETE:
                    // 加载完成，隐藏底部布局
                    loadMoreViewHolder.progressBar.setVisibility(View.INVISIBLE);
                    loadMoreViewHolder.tvLoadText.setVisibility(View.INVISIBLE);
                    break;
                case LOADING_ERROR:
                    // 加载失败，显示错误信息
                    loadMoreViewHolder.progressBar.setVisibility(View.INVISIBLE);
                    loadMoreViewHolder.tvLoadText.setVisibility(View.VISIBLE);
                    loadMoreViewHolder.tvLoadText.setText("加载失败，点击重试");

                    // 点击重试
                    loadMoreViewHolder.itemView.setOnClickListener(v -> {
                        setLoadState(LOADING);
                        // 调用加载更多的方法，可以通过接口回调实现
                        if (onRetryListener != null) {
                            onRetryListener.onRetry();
                        }
                    });
                    break;
                case LOADING_END:
                    // 没有更多数据
                    loadMoreViewHolder.progressBar.setVisibility(View.INVISIBLE);
                    loadMoreViewHolder.tvLoadText.setVisibility(View.VISIBLE);
                    loadMoreViewHolder.tvLoadText.setText("没有更多数据了");
                    break;
            }
        }
    }

    @Override
    public int getItemCount() {
        // 数据项数量 + 1个底部加载更多项
        return datas.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        // 最后一项是加载更多
        if (position == getItemCount() - 1) {
            return TYPE_LOAD_MORE;
        } else {
            return TYPE_ITEM;
        }
    }

    // 设置加载状态
    public void setLoadState(int loadState) {
        this.loadState = loadState;
        notifyItemChanged(getItemCount() - 1);
    }

    // 数据项ViewHolder
     class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView btitleTv;
        TextView bauthorChaoTv;
        TextView bcontTv;
        TextView bchaoTv;

        public ItemViewHolder(View itemView) {
            super(itemView);
            btitleTv = itemView.findViewById(R.id.btitleTv);
            bauthorChaoTv = itemView.findViewById(R.id.bauthorTv);
            bcontTv = itemView.findViewById(R.id.bcontTv);
            bchaoTv = itemView.findViewById(R.id.bchaoTv);
            // 结果项点击事件
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (clickListener != null) {
                // 获取当前position（注意：要用getAdapterPosition()而非getLayoutPosition()）
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) { // 防止position无效
                    clickListener.onItemClick(view, position);
                }
            }
        }
    }

    // 加载更多ViewHolder
    static class LoadMoreViewHolder extends RecyclerView.ViewHolder {
        ProgressBar progressBar;
        TextView tvLoadText;

        public LoadMoreViewHolder(View itemView) {
            super(itemView);
            progressBar = itemView.findViewById(R.id.progress_bar);
            tvLoadText = itemView.findViewById(R.id.tv_load_text);
        }
    }

    // 重试加载监听器
    private OnRetryListener onRetryListener;

    public void setOnRetryListener(OnRetryListener listener) {
        this.onRetryListener = listener;
    }

    public interface OnRetryListener {
        void onRetry();
    }
}
